📌 What is OOPs & The 4 Pillars
OOP makes code reusable, organized, and secure. The 4 main pillars of OOP are Encapsulation (data hiding), Inheritance (code reuse), Polymorphism (multiple forms), and Abstraction (hiding complexity).
1. Which pillar of OOP is responsible for bundling data and methods into a single unit?
Explanation: Encapsulation binds data and the methods that operate on that data together.
2. Which OOP pillar allows a child class to reuse code from an existing parent class?
Explanation: Inheritance allows a new class to inherit attributes and methods from an existing class.
3. What is an "object" in OOP?
Explanation: An object is a concrete instance created from a class blueprint.
4. What does Abstraction mean in OOP?
Explanation: Abstraction hides internal implementation details and exposes only clean interfaces.
Answer: OOP is a programming paradigm that organizes software design around objects (data and behavior) rather than functions and logic alone.
Answer: The 4 pillars are Encapsulation, Abstraction, Inheritance, and Polymorphism.
Answer: Procedural code is a sequence of steps operating on separate data. OOP binds data and functions together into reusable objects.
Answer: Code reusability, modularity, easier debugging, data security, and natural real-world modeling.
self is the car's steering wheel referring to this exact specific car!
📌 Defining Classes & Creating Objects
Use the class keyword to create a class. Inside methods, self must be the first parameter to access instance variables.
1. What keyword is used to create a class in Python?
Explanation: The class keyword defines a new class.
2. What does the self keyword represent inside an instance method?
Explanation: self points to the specific instance calling the method.
3. If Car is a class, what does c = Car() do?
Explanation: Calling a class creates a new instance object.
4. Must self always be the first parameter of an instance method in Python?
Explanation: Python automatically passes the instance as the first argument, so self must be first.
Answer: A class is a blueprint or definition, while an object is a concrete instance of that class living in memory.
Answer: self refers to the current instance of the class, allowing access to its attributes and methods.
Answer: No, self is a very strong convention. Any valid variable name in the first parameter position works, but using self is universal standard.
Answer: Call the class name with parentheses, like: obj = MyClass().
__init__ like the delivery inspection and setup routine at a dealership! The instant a brand new car leaves the production line, __init__ fills the gas tank, sets the owner's name, and calibrates the speedometer!
📌 Initializing Attributes with __init__
__init__ accepts arguments passed when creating an object and assigns them to self.
1. Which special method acts as the constructor in Python?
Explanation: __init__ is the standard initializer/constructor method.
2. When does the __init__ method execute?
Explanation: __init__ executes immediately upon instantiation.
3. Can __init__ return a string or number?
Explanation: Returning any value other than None from __init__ raises a TypeError.
4. How do you pass arguments to __init__?
Explanation: Arguments passed to ClassName(...) are forwarded directly to __init__.
Answer: __init__ is the constructor method in Python, called automatically when a new object is instantiated to initialize attributes.
Answer: Python does not support traditional constructor overloading. However, you can use default arguments or class methods (@classmethod) as alternative constructors.
Answer: __new__ creates the new object instance in memory, while __init__ initializes the newly created instance attributes.
Answer: No. __init__ must return None. Returning any other value raises a TypeError.
📌 Method Types in Python
Instance methods work with individual object data. Static methods are helper functions that do not need object or class data.
1. What decorator marks a method as a class method?
Explanation: @classmethod defines a class-level method.
2. What is the standard first parameter of a @classmethod?
Explanation: cls represents the class itself in a classmethod.
3. Does a @staticmethod require self or cls as its first parameter?
Explanation: Static methods act like plain functions housed inside a class namespace.
4. Can an instance method access instance variables via self?
Explanation: Instance methods have access to self.attribute.
Answer: Instance methods take self (operate on instance data). Class methods take cls with @classmethod (operate on class-level data). Static methods with @staticmethod take neither self nor cls (independent helper functions).
Answer: For factory methods (alternative constructors) or operations that modify class-level state across all instances.
Answer: When you need a utility/helper function that belongs logically inside a class namespace but does not access instance or class state.
Answer: Using the class name or an instance: ClassName.method_name().
📌 Private Variables (__name)
Putting double underscores (__) before a variable name makes it private using name mangling so it cannot be altered accidentally from outside.
1. What prefix indicates a private variable in Python?
Explanation: Two leading underscores trigger Python name mangling for private attributes.
2. What does a single leading underscore (_name) indicate to other developers?
Explanation: _name is a convention signaling internal implementation.
3. What mechanism does Python use internally for double underscore private variables?
Explanation: Name mangling transforms __var into _ClassName__var.
4. What is the recommended way to read private attributes from outside the class?
Explanation: Getter methods provide clean, validated read access.
Answer: Python uses naming conventions: public (no underscore), protected (_single_underscore by convention), and private (__double_underscore with name mangling).
Answer: Python automatically renames private attributes with __ prefix to _ClassName__attributeName to prevent accidental access or subclass override.
Answer: No, Python is a consenting adults language. You can still access them using their mangled name: obj._ClassName__variable.
Answer: To provide controlled, validated read and write access to private attributes.
📌 Parent and Child Classes
Pass the parent class name inside parentheses when defining the child class: class Child(Parent):.
1. How do you make class Dog inherit from class Animal in Python?
Explanation: class Dog(Animal): is the Python syntax for inheritance.
2. Which built-in function calls parent class methods?
Explanation: super() refers to the parent class.
3. What happens when a child class implements a method with the exact same name as the parent class?
Explanation: This is called method overriding.
4. Which function checks if an object is an instance of a given class?
Explanation: isinstance(obj, ClassName) returns True if obj belongs to that class.
Answer: A mechanism where a new class (child/subclass) derives properties and behaviors from an existing class (parent/superclass).
Answer: super() returns a proxy object that delegates method calls to a parent or sibling class in the MRO chain.
Answer: When a child class defines a method with the same name as a method in its parent class, replacing its behavior.
Answer: Single, Multiple, Multilevel, Hierarchical, and Hybrid inheritance.
turn_on()), but each gadget responds in its own unique way!
📌 Duck Typing in Practice
Python cares about what methods an object has, not its explicit class type.
1. What famous phrase explains Duck Typing in Python?
Explanation: Duck typing focuses on what an object can do, not what class it inherits from.
2. Which magic method is implemented to overload the + operator?
Explanation: __add__ defines behavior for the + operator.
3. Can two completely unrelated classes have methods with the same name in Python?
Explanation: Different classes can freely define methods with identical names.
4. What does len("cat") and len([1, 2]) demonstrating same function on different types show?
Explanation: Built-in polymorphism allows len() to work on strings, lists, dicts, etc.
Answer: Polymorphism means "many forms". It allows different objects to respond to the same method call in their own specific way.
Answer: Duck typing is dynamic typing philosophy: Python checks for the presence of methods or attributes at runtime rather than verifying explicit inheritance.
Answer: Allowing built-in operators like +, -, * to perform custom operations on custom objects by defining magic methods like __add__.
Answer: The __add__(self, other) method.
📌 Abstract Base Classes (ABC)
An abstract class cannot be instantiated directly. Child classes MUST implement all abstract methods.
1. Which built-in module is used to create abstract classes in Python?
Explanation: The abc module (Abstract Base Classes) provides ABC and @abstractmethod.
2. Can you create an object directly from an abstract class that has abstract methods?
Explanation: Abstract classes with abstract methods cannot be instantiated directly.
3. What decorator marks a method as abstract?
Explanation: @abstractmethod marks methods that subclasses must implement.
4. What must a subclass do to be instantiated if its parent has abstract methods?
Explanation: Subclasses must override every abstract method before instances can be created.
Answer: Abstraction is the concept of hiding complex implementation details and showing only necessary interface features to the user.
Answer: Using the abc module, inheriting from ABC, and decorating required methods with @abstractmethod.
Answer: No. Trying to create an instance of an abstract class raises a TypeError.
Answer: The child class remains abstract itself and cannot be instantiated.
__str__ tells Python how to print your object, and __len__ tells it what len() should return!
📌 __str__ and __len__ Methods
__str__ controls what print(obj) displays as text. __len__ controls what len(obj) returns.
1. What does "dunder" stand for in Python?
Explanation: Dunder is short for Double Underscore.
2. Which dunder method is called when an object is passed to print() or str()?
Explanation: __str__ returns human-readable string representation.
3. Which method is called by the built-in len() function?
Explanation: __len__ provides the length for custom classes.
4. What dunder method handles equality comparison (==)?
Explanation: __eq__ defines the == comparison.
Answer: Special methods surrounded by double underscores (e.g. __init__, __str__) that Python automatically invokes for built-in operations.
Answer: __str__ is intended to provide an informal, readable string for end users, while __repr__ provides an unambiguous official representation for developers and debugging.
Answer: The __len__(self) method.
Answer: The __eq__(self, other) method.
📌 Method Resolution Order (MRO)
Python uses the C3 Linearization algorithm to resolve the Diamond Problem. You can inspect MRO with ClassName.__mro__.
1. What does MRO stand for in Python?
Explanation: MRO stands for Method Resolution Order.
2. Which algorithm does Python use to compute MRO?
Explanation: Python uses the C3 Linearization algorithm to calculate MRO.
3. How can you inspect the MRO order of a class?
Explanation: .mro() returns the list of classes in resolution order.
4. Does Python support inheriting from more than one parent class?
Explanation: Python natively supports multiple inheritance: class C(A, B):.
Answer: When a child class inherits from two parent classes that both derive from a common grandparent class, creating ambiguity over which grandparent method to call.
Answer: Python uses MRO (Method Resolution Order) calculated via the C3 Linearization algorithm to establish a predictable method search order.
Answer: Call ClassName.mro() or inspect the ClassName.__mro__ attribute.
Answer: Yes: class Child(Parent1, Parent2): is fully supported.
@property like a security guard stationed at the front gate: whenever you ask for temperature, it transparently checks and validates the reading before handing it to you!
📌 Pythonic Getters & Setters with @property
Use @property for getters, and @prop_name.setter for setters. It keeps code clean without calling methods like get_age().
1. What decorator turns a method into a readable property accessed without parentheses?
Explanation: @property turns a method into a getter property accessed as obj.prop.
2. How do you access a @property method named salary on instance emp?
Explanation: Property methods are accessed as attributes without parentheses.
3. How do you create a read-only attribute with @property?
Explanation: Omitting the setter makes the property read-only.
4. What decorator is used to write a setter for a property named price?
Explanation: @price.setter defines the write logic for the property.
Answer: To define getter methods that can be accessed like attributes (e.g. obj.area instead of obj.area()), allowing encapsulation without changing external syntax.
Answer: Use @attribute_name.setter above a method with the same attribute name taking (self, value).
Answer: Yes! Simply define the @property getter without defining a matching @setter.
Answer: Use @attribute_name.deleter to handle the del obj.attribute statement.
📌 1. Dynamic Class Construction with type() & __new__
Instead of the 'class' statement, you can create classes on the fly using type('ClassName', (BaseClasses,), {attributes}). The __new__ method is the true constructor responsible for returning a new instance before __init__ is called.
📌 2. Metaclass Architecture & Singleton Pattern
A metaclass inherits from 'type' and intercepts class creation, allowing you to validate class attributes, enforce coding standards across subclasses, or enforce the Singleton pattern across an entire framework.
1. What is a Metaclass in Python?
Explanation: Just as ordinary objects are instances of a class, classes in Python are instances of a metaclass (by default, 'type').
2. What is the key difference between __new__ and __init__?
Explanation: __new__(cls, ...) is a static method that constructs and returns the instance. __init__(self, ...) initializes the newly created instance.
3. What does calling type('Dog', (Animal,), {'bark': bark_func}) do?
Explanation: The 3-argument signature of type(name, bases, dict) dynamically generates a brand new class at runtime.
4. Which base class must any custom metaclass inherit from in Python?
Explanation: A metaclass must inherit from 'type' (e.g. class MyMeta(type):) to hook into the class instantiation pipeline.
Answer: Metaclasses are appropriate in framework development (Django ORM, Pydantic, SQLAlchemy) for:
1. Class registration: Automatically registering subclasses in a plugin registry.
2. Validation: Enforcing that subclasses override required methods or conform to naming conventions upon import.
3. Attribute transformation: Converting declarative model attributes (e.g. models.CharField()) into database schema columns upon class definition.
Answer: __init_subclass__ is a hook on the base class that executes whenever a subclass is created. It achieves 90% of metaclass validation use cases (such as parameter checking and automatic registration) without the complexity of metaclass inheritance conflicts.
Answer: Python's internal instantiation protocol calls instance = cls.__new__(cls, *args, **kwargs). If and only if the returned object is an instance of cls, Python calls instance.__init__(*args, **kwargs). If __new__ returns a different object (or None), __init__ is skipped entirely.
Answer: In multithreaded environments, two threads might evaluate cls not in cls._instances simultaneously. To make the Singleton thread-safe, wrap the instance creation check in a threading.Lock (double-checked locking pattern).
📌 1. The Descriptor Protocol (__get__, __set__, __delete__)
A descriptor is an object attribute with 'binding behavior', whose attribute access is overridden by methods in the descriptor protocol. If an object defines at least __get__(), it is a descriptor.
📌 2. Data vs Non-Data Descriptors & Attribute Lookup Order
A Data Descriptor defines both __get__() and __set__(). A Non-Data Descriptor defines only __get__() (like regular methods). When looking up an attribute 'obj.x', Python checks Data Descriptors first, then obj.__dict__, then Non-Data Descriptors, then class __dict__.
1. What methods make up the Python Descriptor Protocol?
Explanation: An object is a descriptor if it defines __get__(), __set__(), or __delete__().
2. What is the difference between a Data Descriptor and a Non-Data Descriptor?
Explanation: Data descriptors override instance dictionary (__dict__) lookups; non-data descriptors can be shadowed by entries in the instance's __dict__.
3. What method introduced in Python 3.6 allows a descriptor to know the attribute name it was assigned to in the owning class?
Explanation: __set_name__ is called automatically by Python at class creation time, passing the owner class and attribute name.
4. How does Python implement standard methods on classes under the hood?
Explanation: Functions in Python implement __get__(). When accessed on an instance, function.__get__(instance, owner) returns a bound method object.
Answer: When looking up obj.attr:
1. Check class hierarchy for a Data Descriptor with attr; if found, call __get__.
2. Check obj.__dict__['attr'] (instance dictionary).
3. Check class hierarchy for a Non-Data Descriptor; if found, call __get__.
4. Check class hierarchy for standard class attributes in Class.__dict__.
5. Call __getattr__(obj, 'attr') if defined; otherwise raise AttributeError.
Answer: property is a C-implemented Data Descriptor class. It stores getter, setter, and deleter functions. Its __get__ invokes the getter; its __set__ invokes the setter, giving method calls the clean appearance of direct attribute access.
Answer: In Django, model fields (e.g. name = models.CharField(...)) are descriptors. When you access user.name, the descriptor's __get__ retrieves the column value; when you assign user.name = 'Priya', the descriptor's __set__ marks the field as dirty for the next SQL UPDATE.
Answer: The instance argument passed to __get__(self, instance, owner) will be None. Descriptors typically check if instance is None: return self to return the descriptor instance itself when accessed on the class.
@dataclass like ordering a pre-furnished apartment! You don't have to manually build the bed, sofa, and dining table (__init__, __repr__, __eq__)—Python builds them automatically for you!
📌 1. Modern Data Classes with @dataclass
The @dataclass decorator automatically writes __init__(), __repr__(), __eq__(), and optional comparison methods based on type annotations, with support for frozen (immutable) instances and default factories.
📌 2. High-Performance Memory Optimization with __slots__
By default, every Python instance stores attributes in a dynamic dictionary (__dict__). By defining __slots__ = ('attr1', 'attr2'), Python allocates a fixed array of pointers, eliminating __dict__ overhead and preventing arbitrary dynamic attribute additions.
1. What methods does the @dataclass decorator generate automatically by default?
Explanation: @dataclass inspects class type annotations and generates __init__, __repr__, and __eq__ automatically.
2. What happens if you define a dataclass with @dataclass(frozen=True)?
Explanation: frozen=True makes instances read-only/immutable, which also allows Python to generate a hash function so instances can be used as dictionary keys.
3. How does __slots__ optimize memory consumption in Python classes?
Explanation: By replacing the dynamic __dict__ with a fixed tuple of attribute descriptors, __slots__ saves significant RAM and speeds up attribute access.
4. Why should you use 'field(default_factory=list)' instead of 'items: list = []' in a dataclass?
Explanation: Just like default arguments in functions, mutable defaults like [] would be shared across all instances. default_factory creates a fresh list for each new instance.
Answer: Choose @dataclass when you need mutable state, inheritance, default factories, or clean property methods without boilerplate. Choose NamedTuple when you need lightweight immutable tuples that unpack by index. Choose a standard class when the class has complex custom behaviors and business logic rather than just holding data.
Answer: Yes! In Python 3.10+, you can simply pass @dataclass(slots=True), and Python will automatically generate the __slots__ tuple matching the type annotations, combining boilerplate-free dataclasses with high-speed memory optimization.
Answer:
1. You cannot add dynamic attributes at runtime that are not in __slots__.
2. Multiple inheritance with multiple slotted parent classes can fail if their slots overlap.
3. Instances cannot be weakly referenced unless '__weakref__' is explicitly included in __slots__.
Answer: __post_init__(self) is called automatically at the end of the generated __init__(). It is used to perform custom data validation, compute derived fields, or transform inputs after initial assignment.
📌 1. Pattern Matching on Class Instances
Structural pattern matching can match against class types and extract their attributes directly in the case clause, replacing nested if-isinstance chains.
📌 2. Guard Conditions & Destructuring Nested Sequences
Case patterns can include 'if' guards to enforce value constraints, use the wildcard '_' for fallback defaults, and capture matched elements into variables with the 'as' keyword.
1. Which Python version introduced Structural Pattern Matching via match-case?
Explanation: Structural pattern matching was officially introduced in Python 3.10 via PEP 634.
2. What symbol is used as the wildcard / default fallback pattern in a match-case statement?
Explanation: The underscore 'case _:' acts as the wildcard catch-all case, matching any value.
3. What is an 'if guard' inside a case clause?
Explanation: Guard conditions ('case pattern if condition:') allow filtering patterns based on runtime expressions.
4. Which dunder attribute on a class controls which positional arguments can be matched in 'case MyClass(a, b):'?
Explanation: __match_args__ = ('attr1', 'attr2') defines the mapping of positional pattern arguments to object attributes.
Answer: Traditional switch-case only matches primitive values (integers, strings). Python's Structural Pattern Matching: 1. Destructures data structures (lists, tuples, dicts). 2. Validates object types and unpacks attributes. 3. Evaluates runtime guard conditions with if. 4. Binds sub-patterns to local variables.
Answer: @dataclass automatically defines __match_args__ based on the order of fields in the dataclass definition, making all dataclasses immediately compatible with positional pattern matching without any extra code.
Answer: You can match multiple alternative values in a single case statement using the pipe operator: case 401 | 403: return 'Authentication/Permission Error'.
Answer: No. Just like for loops and with blocks in Python, variables bound during pattern matching exist in the enclosing function scope.
📌 1. Creational Patterns: Singleton & Factory Pattern
A Factory encapsulates object instantiation logic, allowing client code to request an object by specification rather than instantiating concrete classes directly.
📌 2. Behavioral Patterns: Strategy & Observer Patterns
The Strategy pattern allows choosing an algorithm's behavior at runtime (e.g. discount calculation, sorting). The Observer pattern enables decoupled event-driven communication between publishers and subscribers.
1. In modern Python, what is the cleanest and most natural way to create a Singleton without complex class boilerplate?
Explanation: Python module caching (sys.modules) ensures that when you instantiate an object inside a module, every importing file receives the exact same single instance.
2. Which design pattern is used when you want to dynamically swap algorithms or business calculations at runtime?
Explanation: The Strategy pattern encapsulates interchangeable algorithms, allowing them to be swapped dynamically at runtime.
3. What is the primary role of the Factory Pattern?
Explanation: The Factory Pattern delegates object creation to a factory method, decoupling client code from concrete implementations.
4. Which design pattern decouples event publishers from multiple subscribers listening for changes?
Explanation: The Observer pattern establishes a one-to-many dependency so when the Subject changes state, all registered Observers are notified automatically.
Answer: Python has first-class functions, duck typing, and dynamic attributes. Patterns like Strategy or Command require multiple interfaces and abstract classes in Java; in Python, you can simply pass a function or lambda directly.
Answer: High-level modules should depend on abstractions, not concrete implementations. In Python, DI means passing dependencies (like database clients or email senders) into a class constructor rather than hardcoding self.db = RealPostgres() inside the class, making unit testing with mocks effortless.
Answer: An Adapter translates an incompatible third-party interface into the interface expected by your application. For example, adapting an XML-based legacy banking API response into the JSON dict format expected by your modern payment service.
Answer: Overused Singletons introduce global mutable state, tightly couple code to concrete classes, and make unit testing difficult because state leaks between separate test runs.
typing.Protocol like an audition for a movie role: as long as an actor can sing and dance on stage (duck typing), the director hires them regardless of their family background!
📌 1. Nominal Subtyping (abc.ABC) vs Structural Subtyping (Protocol)
With abc.ABC, a class must explicitly inherit from the abstract base class (nominal subtyping). With typing.Protocol, any class that implements the expected methods automatically conforms to the interface without inheriting from it (structural subtyping).
📌 2. Runtime Checkable Protocols with @runtime_checkable
By default, Protocols are only checked statically by type checkers like MyPy. Decorating a Protocol with @runtime_checkable allows you to use isinstance() and issubclass() at runtime to verify structural conformity.
1. What is the primary difference between abc.ABC and typing.Protocol in Python?
Explanation: Protocols implement Structural Subtyping (static duck typing). If a class has the required methods, it satisfies the Protocol without inheriting from it.
2. What decorator allows a typing.Protocol to be checked at runtime using isinstance()?
Explanation: @runtime_checkable inspects the presence of attributes/methods at runtime when isinstance(obj, MyProtocol) is called.
3. What does the ellipsis (...) inside a Protocol method definition represent?
Explanation: In typing stubs and Protocols, the ellipsis (...) is standard Python syntax indicating an empty signature to be implemented by conforming types.
4. Which popular programming language uses structural typing similar to Python's typing.Protocol as its core type system?
Explanation: TypeScript (interfaces) and Go (interfaces) both use structural typing where types match by structure rather than explicit inheritance.
Answer: Nominal Subtyping (Java, C++, abc.ABC) requires a class to explicitly declare its parent: class Cat(Animal). If it doesn't inherit, it is not an Animal.
Structural Subtyping (typing.Protocol, Go, TypeScript) checks the shape of the class. If a class implements all methods defined in the Protocol, it is considered a valid subtype without any explicit inheritance.
Answer: If your library defines an abc.ABC, user code must import your base class and inherit from it, creating tight coupling. With Protocol, users can pass any object from standard libraries or third-party packages that implements the required methods without coupling their classes to your library.
Answer: @runtime_checkable only checks whether the attribute or method exists; it does NOT inspect method signatures, parameter types, or return types at runtime due to Python performance considerations.
Answer: You can create generic protocols: class Repository(Protocol[T]): def get_by_id(self, id: int) -> T: .... This allows creating generic repositories for different database entities with full static type safety in MyPy.